package com.cyc.demo2;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author:CYC
 * @Date: Created in 2020/7/1 14:37
 * @Description:
 */
public class SaeTickDemo02 {

    public static void main(String[] args) {
        Tick2 tick = new Tick2();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                tick.sell();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                tick.sell();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                tick.sell();
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                tick.sell();
            }
        },"D").start();
    }
}

class Tick2{
    private int ticket = 50;

    private Lock lock = new ReentrantLock();


    //synchronized本质是 队列 锁
    public void sell(){
        lock.lock();
        try{
            //业务代码
            if (ticket>0){
                System.out.println(Thread.currentThread().getName()+"卖出了"+ticket--+" 剩下："+ticket);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
